/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.formmetadata.i18n.component.strategy.i18nresourcestrategy;

import com.inspur.edp.lcm.metadata.api.entity.I18nResourceItem;
import com.inspur.edp.lcm.metadata.api.entity.I18nResourceItemCollection;
import com.inspur.edp.web.common.utility.StringUtility;
import com.inspur.edp.web.formmetadata.i18n.I18nResourceItemManager;
import com.inspur.edp.web.formmetadata.i18n.component.ComponentUtility;
import com.inspur.edp.web.formmetadata.i18n.constant.I18nResourceConstant;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * html 标签国际化参数提取
 *
 * @author guozhiqi
 */
public class HtmlTemplateI18nResourceStrategy extends AbstractI18nResourceStrategy {
    private Pattern extractPattern = null;
    private Pattern specificPattern = null;
    private final char danYinHao = '\'';
    private final char shuangYinHao = '\"';

    public HtmlTemplateI18nResourceStrategy() {
        // 用于匹配{{}}结构的字符
        this.extractPattern = Pattern.compile("(?<=\\{\\{)[^}]*(?=\\}\\})");

        // 用于匹配 ${Title:"name"} 类似的结构
        this.specificPattern = Pattern.compile("\\$\\{([^\\}]+):([^\\}]+)\\}");

    }

    /**
     * 获取组件属性中多语资源项集合
     *
     * @param i18nResourceItemBaseId
     * @param currentComponent
     * @return
     */
    @Override
    protected I18nResourceItemCollection extractAttributeI18nResourceItemCollection(String i18nResourceItemBaseId, HashMap<String, Object> currentComponent) {
        // 从html属性中提取多语字段
        I18nResourceItemCollection i18nResourceItemCollection = new I18nResourceItemCollection();

        I18nResourceItemCollection htmlI18nResourceItemCollection = ExtractComponentHtmlI18nResourceItemCollection(i18nResourceItemBaseId, currentComponent);
        if (htmlI18nResourceItemCollection.size() > 0) {
            i18nResourceItemCollection.addRange(htmlI18nResourceItemCollection);
        }

        return i18nResourceItemCollection;
    }

    private I18nResourceItemCollection ExtractComponentHtmlI18nResourceItemCollection(String i18nResourceItemBaseId, HashMap<String, Object> currentComponent) {
        I18nResourceItemCollection i18nResourceItemCollection = new I18nResourceItemCollection();

        // 从html属性中提取多语资源
        String htmlValue = ComponentUtility.getInstance().getHtml(currentComponent);
        if (StringUtility.isNullOrEmpty(htmlValue)) {
            return i18nResourceItemCollection;
        }

        Matcher matcher = this.extractPattern.matcher(htmlValue);
        while (matcher.find()) {
            String i18nResourceExpress = matcher.group();
            int expressDelimiterIndex = i18nResourceExpress.indexOf("|");
            // {{'key'|lang:lang:''}}
            if (expressDelimiterIndex > 0) {
                // 判断是否包含末尾的填充数值
                String componentLangValue = i18nResourceExpress.substring(expressDelimiterIndex + 1).trim();
                // 按照 lang:lang:'defaultValue'的形式
                String componentDefaultLangValue = getLangDefaultValue(componentLangValue);
                if (componentDefaultLangValue == null) {
                    // 进行下一个的Html标签解析
                    continue;
                }

                // 构造对应的国际化key
                String componentIdStr = i18nResourceExpress.substring(0, expressDelimiterIndex).trim();
                String trimedComponentIdStr = this.trimStringWith(componentIdStr, Arrays.asList(danYinHao, shuangYinHao));

                I18nResourceItem i18nResourceItem = I18nResourceItemManager.createI18nResourceItem(i18nResourceItemBaseId, trimedComponentIdStr, componentDefaultLangValue, componentDefaultLangValue);

                this.addInCollection(i18nResourceItemCollection, i18nResourceItem);
            }
        }

        Matcher specificMatcher = this.specificPattern.matcher(htmlValue);

        List<String> resourceIdList = new ArrayList<>();
        while (specificMatcher.find()) {
            int groupCount = specificMatcher.groupCount();
            if (groupCount != 2) {
                continue;
            }
            String firstTitle = specificMatcher.group(1).trim();
            if (firstTitle == null) {
                continue;
            }

            while (firstTitle.startsWith("\"") || firstTitle.startsWith("'")) {
                firstTitle = firstTitle.substring(1);
            }

            while (firstTitle.endsWith("\"") || firstTitle.endsWith("'")) {
                firstTitle = firstTitle.substring(0, firstTitle.length() - 1);
            }

            String secondValue = specificMatcher.group(2);

            String currentComponentType = ComponentUtility.getInstance().getType(currentComponent);
            String currentComponentId = ComponentUtility.getInstance().getId(currentComponent);

            String generatedComponentId = currentComponentType + I18nResourceConstant.SECOND_LEVEL_DELIMITER + currentComponentId + I18nResourceConstant.SECOND_LEVEL_DELIMITER + firstTitle;

            // 确保添加到资源项的key 不进行重复
            if (!resourceIdList.contains(generatedComponentId)) {
                while (secondValue.startsWith("\"") || secondValue.startsWith("'")) {
                    secondValue = secondValue.substring(1);
                }

                while (secondValue.endsWith("\"") || secondValue.endsWith("'")) {
                    secondValue = secondValue.substring(0, secondValue.length() - 1);
                }
                I18nResourceItem i18nResourceItem = I18nResourceItemManager.createI18nResourceItem(i18nResourceItemBaseId, generatedComponentId, secondValue, secondValue);
                this.addInCollection(i18nResourceItemCollection, i18nResourceItem);

                resourceIdList.add(generatedComponentId);
            }
        }


        return i18nResourceItemCollection;
    }

    /**
     * 从html结构定义中提取对应的多语配置值
     *
     * @param componentLangValue lang:lang:'defaultValue'
     * @return
     */
    private String getLangDefaultValue(String componentLangValue) {
        if (StringUtility.isNullOrEmpty(componentLangValue)) {
            return null;
        }
        String[] splitArray = componentLangValue.split(":");
        // 读取第三个参数中国际化配置参数值
        if (splitArray != null && splitArray.length >= 3) {
            // 认定第三个参数为国际化默认值
            String langDefaultValue = splitArray[2];
            return this.trimStringWith(langDefaultValue, Arrays.asList(danYinHao, shuangYinHao));
        }

        return null;
    }

    /**
     * 移除字符串两端指定的字符
     *
     * @param source
     * @param beTrim
     * @return
     */
    public String trimStringWith(String source, List<Character> beTrim) {
        int st = 0;
        int len = source.length();
        char[] val = source.toCharArray();

        while ((st < len) && (beTrim.contains(val[st]))) {
            st++;
        }
        while ((st < len) && (beTrim.contains(val[len - 1]))) {
            len--;
        }
        return ((st > 0) || (len < source.length())) ? source.substring(st, len) : source;
    }
}
